/*
 * @Descripttion: 
 * @Author: xgh
 * @Date: 2022-08-31 10:13:27
 * @LastEditors: xgh
 * @LastEditTime: 2022-09-09 12:38:09
 */
var express = require('express');
let svgCaptcha = require('svg-captcha'); // 验证码
var query = require('../connent/mysqlPool') // 引入数据库连接池文件
var uuid = require('node-uuid');
var router = express.Router();
// 创建验证码
router.get('/getcode', function (req, res, next) {
  let code = svgCaptcha.create({
    color: true, // 彩色
    width: 100, //  宽度
    height: 40, // 高度
    fontSize: 48, // 字体大小
    size: 4, // 验证码的长度
    noise: 3, // 干扰线条
    ignoreChars: '0oO1ilI' // 验证码字符中排除 0o1i
  });
  req.session = code.text.toLowerCase();
  res.cookie('code', req.session);
  res.type('svg'); //响应类型
  res.send(code.data); // 往session，cookie中都存入一个验证码，并且把验证码显示在页面上
});


/* 注册 */
router.post('/register', (req, res) => {
  let username = req.body.username;
  let password = req.body.password;
  let id_card = req.body.id_card;
  let phone = req.body.phone;
  let role = 0; //普通用户
  let del_flag = 0
  let avatar = ''
  let department = ''
  let insertSql = "insert into user(username,password,id_card,phone,department,role,del_flag,avatar) values(?,?,?,?,?,?,?,?)"
  let querySql = "select username from  user where username = ?"
  query(querySql, [username], (err, result, fields) => {
    if (result.length === 0) {
      query(insertSql, [username, password, id_card, phone, department, role, del_flag, avatar], (err, result, fields) => {
        if (err) {
          console.log('[SELECT ERROR]:', err.message)
        }
        res.send({
          data: {
            count: 0
          }
        }) // 服务器响应请求
      })
    } else {
      res.send({
        data: {
          count: 1
        }
      })
    }
  })
})



/* =====================================================用户登陆===================================== */

/* 登陆 */
router.post('/login', (req, res) => {
  let username = req.body.username;
  let password = req.body.password;
  let usercode = req.body.code.toLowerCase();
  let querySql = "select * from  user where username = ? and password=?"
  let queryuser = "select * from  user where username = ?"
  let code = req.cookies.code

  //判断用户是否存在
  query(queryuser, [username], (err, result, fields) => {
    if (result.length == 0) {
      res.send({
        code: 0,
        message: "账号不存在"
      })
    } else {
      if (usercode != code) {
        res.send({
          code: 0,
          message: "验证码错误"
        })
      } else {
        query(querySql, [username, password], (err, result, fields) => {
          if (result.length == 0) {     //登陆失败
            res.send({
              code: 1,
            })
          } else {                      //登陆成功
            res.send({
              code: 2,
              data: result
            })
          }
        })
      }
    }
  })
})

/* 用户登陆错误次数 */
router.get('/errcount', (req, res) => {
  let username = req.query.username;
  let id = uuid.v1()
  let err_count = 6
  let errcountsql = "select * from err_login where username = ? "
  let adderrcountsql = "insert into err_login(id,username,err_count) values(?,?,?)"
  let updateerrcountsql = "update err_login set err_count=? where username = ?"

  logRecordSql = "insert into user_log_info values(?,?,?,?,?,?,?,?)"
  query(errcountsql, [username], (err, result, fields) => {
    if (result.length == 0) {
      // 不存在，添加
      query(adderrcountsql, [id, username, err_count], (err, result, fields) => {})
      res.send({
        message: `密码错误，还剩${err_count}次尝试机会`,
        count: err_count
      })
    } else {
      query(errcountsql, [username], (err, result, fields) => {
        // 获取剩余次数
        let errCount = result[0].err_count - 1
        // 更新次数
        if (errCount >= 0) {
          query(updateerrcountsql, [errCount, username], (err, result, fields) => {
            if (errCount === 0) {
              res.send({
                message: `当前密码错误次数已达上限,请24小时后再登陆`,
                count: errCount
              })
            } else {
              res.send({
                message: `密码错误，还剩${errCount}次尝试机会`,
                count: errCount
              })
            }
          })
        }
      })
    }
  })
})

/* 超过24小时，恢复用户错误登陆次数 */
router.get("/restorecount", (req, res) => {
  let username = req.query.username;
  let errCount = 6 //恢复错误次数 6次
  let updateerrcountsql = "update err_login set err_count=? where username = ?"
  query(updateerrcountsql, [errCount, username], (err, result, fields) => {
    res.send({
      message: `密码错误，还剩${errCount}次尝试机会`,
      count: errCount
    })
  })
})

/* 删除用户错误登陆信息 */
router.delete("/deleteerr", (req, res) => {
  let username = req.query.username;
  let deleteerrcountsql = "DELETE from `err_login` where username=?"
  query("select * from err_login where username = ?", [username], (err, result, fields) => {
    if (result.length != 0) {
      query(deleteerrcountsql, [username], (err, result, fields) => {})
    }
  })
})


/* =====================================================用户操作===================================== */

/* 获取用户信息 */
router.get('/userinfo', (req, res) => {
  query("select * from user", (err, result, fields) => {
    res.send({
      code: 1,
      data: result
    })
  })
})  

router.get('/getuserbyid', (req, res) => {
  query("select * from user where id=?",req.query.id, (err, result, fields) => {
    res.send({
      code: 1,
      data: result
    })
  })
})

/* 分页获取用户数据 */
router.get('/getuser', (req, res) => {
  let params = req.query
  let current = parseInt(params.current)
  let pageSize = parseInt(params.pageSize)
  query("select * from user" + ' limit ' + ((current - 1) * pageSize) + ',' + pageSize, (err, result, fields) => {
    if (err) {
      console.log('[SELECT ERROR]:', err.message)
    }
    res.send({
      data: result
    }) // 服务器响应请求
  })
})

/* 删除用户 */
router.get('/deleteuser', (req, res) => {
  const sql = "delete from user where id='" + req.query.id + "'"
  query(sql, (err, result, fields) => {
    if (err) {
      console.log('[SELECT ERROR]:', err.message)
    }
    res.send({
      data: result
    })
  })
})

/* 修改 */
router.post('/updateuserinfo', (req, res) => {
  const updateUserSql = "update user set ? where id=?"
  let userInfo = req.body
  userInfo.role === "管理员" ? userInfo.role = 1 : userInfo.role=0
  query(updateUserSql,[req.body,req.body.id],(err, result, fields) => {
    if (err) {
      console.log('[SELECT ERROR]:', err.message)
    }
    res.send({
      message:"更新成功"
    })
  })
})

/* 添加 */
router.post('/adduserinfo', (req, res) => {
  let userInfo = req.body
  let searchSql = "select * from user where username = ?"
  query(searchSql, [userInfo.username], (err, result, fields) => {
    if (result.length !== 0) {
      res.send({
        code:0,
        message: "该用户已存在，请重新添加"
      })
    }else{
      let username = req.body.username;
      let password = req.body.password;
      let id_card = req.body.id_card;
      let phone = req.body.phone;
      let role = req.body.role==="管理员" ? 1:0; 
      let department = req.body.department
      let del_flag = 0
      let avatar = ''
      let addUserSql = "insert into user(username,password,id_card,phone,department,role,del_flag,avatar) values(?,?,?,?,?,?,?,?)"
      query(addUserSql, [username,password,id_card,phone,department,role,del_flag,avatar], (err, result, fields) => {
        if(result!==0){
          res.send({
            code: 1,
            message: "添加成功"
          })
        }
      })
    }
  })
})



/* =====================================================搜索===================================== */


/* 分组搜索 */
router.post('/groupsearch', (req, res) => {
  let departments = req.body;
  let groupSearchSql = ''
  let groupSql = ""
  for (var i = 0; i < departments.length; i++) {
    if(i===0){
      groupSql = `department =? `
    }else{
      groupSql += `or department =? `
    }
  }
  groupSearchSql = "select * from user where " + groupSql
  console.log(groupSearchSql);
  query(groupSearchSql, departments, (err, result, fields) => {
    res.send({
      data: result
    })
  })
})

/* 模糊搜索 */
router.get('/tosearch', (req, res) => {
  const sql = "SELECT * FROM user where  username LIKE ? or id_card LIKE ? or phone LIKE ?"
  let conditions = req.query.username+'%' 
  query(sql, [conditions, conditions, conditions], (err, result, fields) => {
    if (err) {
      console.log('[SELECT ERROR]:', err.message)
    }
    res.send({
      data: result
    }) // 服务器响应请求
  })
})




module.exports = router;